﻿/**
 * @Description 基础框架服务调用实例-主从表服务
 * @Author  guoyanfei
 */

var masterServices = masterServices || {};
var serviceUrl = '/gdp'
var postPath = '/gdp'
masterServices.prototype = {
    init: function () {//初始化
        masterServices.prototype.createMasterTable();
        masterServices.prototype.setSearchColumn();
        masterServices.prototype.eventSearch();
        masterServices.prototype.generateDetailTab();
    },
    createMasterTable: function () {//创建主表信息
        $("#masterTable").bootstrapTable('destroy').bootstrapTable({
            url: postPath + '/business/extMasterServer/queryMasterTableList',
            undefinedText: '-',
            method: 'get',
            pagination: true,
            striped: true,
            cache: false,
            pageList: [5, 10, 20],
            toolbar: "#toolbar",
            showColumns: true,
            showRefresh: true,
            singleSelect:true,
            sidePagination: "server",
            responseHandler: function (res) {
                // solve two question 1. delay handle response 2. solve the handle page render
                setTimeout(masterServices.prototype.generateDetailData, 400);
                return handleResponseResult(res);
            },
            queryParams: masterServices.prototype.queryParamsMaster,
            uniqueId: "guid",
            columns: masterServices.prototype.getShowField(),
            onCheck: function (row) {
                masterServices.prototype.generateDetailData(row);
            },
            onUncheck: function (row) {
                $('[id^=td]').each(function () {
                    $(this).html("");
                });
            }
        });
    },
    queryParamsMaster:function(pageReqeust){//主表查询条件
        var temp = {
            serviceID: serviceId,
            pageNO: pageReqeust.offset / pageReqeust.limit + 1,
            pageSize: pageReqeust.limit,
            conQuery: masterServices.prototype.setSearchParams()
        };
        return temp;
    },
    getShowField: function () {//获取表格显示列数据
    	var coltxt = "{ field: 'state', checkbox: true, align: 'center', valign: 'middle' }";
        var columns = [];
        columns.push({
            field: 'state', checkbox: true, align: 'center', valign: 'middle', formatter: function (value, row, index) {
                if (index == 0) {
                    return {
                        checked:true
                    }
                }
            }
        });
        var columnData = new Array();
        $.ajax({
            url: postPath + '/business/extMasterServer/queryTableShowField',
            type: 'get',
            async: false,
            data: { serviceID: serviceId },
            dataType: "json",
            success: function (data) {
                columnData = data.data;
            },
            error: function () {
                showMsg("显示列数据加载失败!","error");
            }
        });
        $.each(columnData, function (i, e) {
            columns.push({ "field": e.fieldname, "title": e.fieldnamecn, "align": 'center', "valign": 'middle' });
            coltxt +="<br/>   ,{ field: '"+e.fieldname+"', title: '"+e.fieldnamecn+"', align: 'center', valign: 'middle' }"
        });
        $("#s_col").html(coltxt);
        return columns;

    },
    setSearchColumn: function () {//设置表格查询列
        var columnData = new Array();
        $.ajax({
            url: postPath + '/business/extMasterServer/queryTableQueryField',
            type: 'get',
            async: false,
            data: { serviceID: serviceId },
            dataType: "json",
            success: function (data) {
                columnData = data.data;
            },
            error: function () {
                showMsg("列数据加载失败!","error");
            }
        });
        if (columnData != null) {
        	$.each(columnData, function (i, e) {
            	var fieldname = "search"+e.fieldname;
            	fieldname = fieldname.replace("@","_");
                switch (e.showtype) {
                    case "0"://文本框
                        $("#txtSearch").append("<label style='margin-left:10px;' for='" + fieldname + "'>" + e.fieldnamecn + "：</label>");
                        $("#txtSearch").append("<input id='" + fieldname + "' placeholder='请输入" + e.fieldnamecn + "' type='text' class='form-control' >");
                        break;
                    case "1"://下拉框
                        $("#txtSearch").append("<label style='margin-left:10px;' for='" + fieldname + "'>" + e.fieldnamecn + "：</label>");
                        var strtxt = "<select id='" + fieldname + "'  class='form-control' >"
                                       + "<option value=''>请选择</option>";
                        if (e.enumvalue != null && e.enumvalue != "") {
                            var enums = e.enumvalue.split(',');
                            for (var i = 0; i < enums.length; i++) {
                                var eb = enums[i].split(':');
                                strtxt += "<option value='"+eb[0]+"'>"+eb[1]+"</option>";
                            }
                        }
                        strtxt += "</select>";
                        $("#txtSearch").append(strtxt);
                        break;
                    case "4"://日期框
                        $("#txtSearch").append("<label style='margin-left:10px;' for='" + fieldname + "'>" + e.fieldnamecn + "：</label>");
                        $("#txtSearch").append("<input id='" + fieldname + "' data-date-format=\"yyyy-mm-dd\" type='text' class='form-control' >");
                        $("#" + fieldname + "").datetimepicker();
                        break;
                }
            });

        }
    },
    setSearchParams: function () {//设置查询参数
        var searchParams = [];
        var columnData = new Array();
        $.ajax({
            url: postPath + '/business/extMasterServer/queryTableQueryField',
            type: 'get',
            async: false,
            data: { serviceID: serviceId },
            dataType: "json",
            success: function (data) {
                columnData = data.data;
            },
            error: function () {
                showMsg("列数据加载失败!","error");
            }
        });
        if (columnData != null) {
        	 $.each(columnData, function (i, e) {
             	var fieldname = "search"+e.fieldname;
             	fieldname = fieldname.replace("@","_");
                 if ($('#' + fieldname).val() != null && $('#' + fieldname).val() != 'undefined' && $('#' + fieldname).val() != "") {
                 	  if (searchParams == "") {
                           searchParams = "\"" + e.fieldname + "\":\""+ $('#' + fieldname).val()+"\"";
                       } else { 
                           searchParams += ",\"" + e.fieldname + "\":\"" + $('#' + fieldname).val() + "\"";
                       }
                 }
             });
             searchParams = "{" + searchParams + "}";
        }
        return searchParams;
    },
    eventSearch: function () {//查询操作
        $("#btn_search").click(function () {
            $("#masterTable").bootstrapTable('refresh');
            setTimeout(masterServices.prototype.generateDetailData, 400);
        });
    },
    getDetailShowField: function () {//查询从表显示字段
        var detailColumnData = new Array();
        $.ajax({
            url: postPath + '/business/extMasterServer/queryTableDetailShowField',
            type: 'get',
            async: false,
            data: { serviceID: serviceId },
            dataType: "json",
            success: function (data) {
                detailColumnData = data.data;
            },
            error: function () {
                showMsg("显示列数据加载失败!","error");
            }
        });
        return detailColumnData;
    },
    getMasterTablePrimaryKey:function(){//查询主表主键
        var primaryKeyColn = "";
        $.ajax({
            url: postPath + '/business/extMasterServer/queryMasterTablePrimaryKey',
            type: 'get',
            async: false,
            data: { serviceID: serviceId},
            success: function (data) {
                primaryKeyColn = data.data;
            },
            error: function () {
                showMsg("主表主键加载失败!","error");
            }
        });
        return primaryKeyColn;
    },
    getDetailData: function () {//查询从表数据 List<Map<slaveTableName, slaveTable>>

        var primaryKeyColn = masterServices.prototype.getMasterTablePrimaryKey();

        var guid = "";
        var row = $("#masterTable").bootstrapTable("getSelections");
        if (row.length  == 0) {
            return;
        } else {
            var pknames = primaryKeyColn.split(",");
            $.each(pknames,function(i,e){
//                var primaryKey = row[0].rows[0]['' + e + '']
                var primaryKey = row[0]['' + e + '']


                if(guid == ""){
                    guid = primaryKey
                }else{
                    guid += "," + primaryKey;
                }
            });

        }

        var detailData = new Array();
        $.ajax({
            url: postPath + '/business/extMasterServer/querySlaveTBbyMasterID',
            type: 'get',
            async: false,
            data: { serviceID: serviceId, guid: guid},
            dataType: "json",
            success: function (data) {
                detailData = data.data;
            },
            error: function () {
                showMsg("从表数据加载失败!","error");
            }
        });
        return detailData;
    },
    generateDetailTab: function () {//生成从表tab
        var detailColumnData = masterServices.prototype.getDetailShowField();
        var count = 0;
        $.each(detailColumnData, function (i,e) {
            count++;
            var tabclass = "";
            if (count == 1) {
                tabclass = "active";
            } else {
                tabclass = "";
            }

            $('#ultab').append('<li class="' + tabclass + '"><a href="#tab' + count + '" data-toggle="tab" style="min-width:100px;">' + i + '</a></li>');
            var tableh = "<div class='bootstrap-table' style='margin-top:10px;'><table class='bootstrap-table table table-hover table-striped'><thead><tr>";
            var data = JSON.parse(e);
            $.each(data, function (j, k) {
                tableh += "<th style='border:solid 1px #ddd; height:35px; text-align:center;'>" + k.fieldnamecn + "</th>";
            });
            tableh += "</tr></thead><tbody id='td" + count + "'></tbody>";

            tableh +="</table></div>";
            $('#tabcount').append('<div class="tab-pane fade in ' + tabclass + '" id="tab' + count + '">' + tableh + '</div>');
        });
    },
    generateDetailData: function (selectRow) {//生成从表数据
        var detailDataList = masterServices.prototype.getDetailData(selectRow);

        var detailData = [];// only access first element

        if(detailDataList != null && detailDataList.length > 0){
            detailData = detailDataList[0];// only access first element

        }
        var count = 0;
        // here is require first element in sub set
        $.each(detailData, function (j, e) {
            count++;
            var tdcount = "";
            var data = e;
            // here is contain multiple slave table from masterTable condition
            for (var i = 0, L = data.length; i < L; i++) {
                tdcount+='<tr>';
                for (var k in data[i])
                    tdcount += '<td style="border-left:solid 1px #ddd; border-right:solid 1px #ddd; border-bottom:solid 1px #ddd; vertical-align: middle; text-align:center;">' + data[i][k] + '</td>';
                tdcount += '</tr>';
            }
            $("#td" + count + "").html("");
            $("#td"+count+"").append(tdcount);
        })
    }

};

$(function () {
    $("#sp_seviceUrl").append("服务地址：" + postPath + "/business/extMasterServer/queryMasterTableList");
    $("#sp_seviceUrl").append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;服务ID：" + serviceId);
    $("#show_serviceUrl").append(postPath);
    $("#show_serviceId").append(serviceId);
    
    masterServices.prototype.init();
})

function showMsg(text, icon) {
    $.toast().reset('all');
    $.toast({
        text: text,
        icon: icon,
        showHideTransition: 'fade',
        allowToastClose: true,
        hideAfter: 1500,
        stack: false,
        position: 'top-right',
        textAlign: 'left',
        loader: true,
        loaderBg: '#9ec600',
    });
}
